package com.hqbzl.c1.cass;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class TestCas1 {
    static void demo(Account account) {
        CountDownLatch cdt = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                AtomicInteger amount = new AtomicInteger(10);
                account.withdraw(amount);
                cdt.countDown();
            }, "th-" + i).start();
        }
        try {
            cdt.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("account.getBalance() = " + account.getBalance());
    }

    public static void main(String[] args) {
        AtomicInteger amount = new AtomicInteger(1000);
        final Account account = new UnSafeAccount1(amount);
        System.out.println("account.getBalance() = " + account.getBalance());
        demo(account);
    }

    interface Account {

        AtomicInteger getBalance();

        void withdraw(AtomicInteger amount);


    }

    static class UnSafeAccount1 implements Account {
        private AtomicInteger balance;

        UnSafeAccount1(AtomicInteger balance) {
            this.balance = balance;
        }

        @Override
        public void withdraw(AtomicInteger amount) {
            this.balance.addAndGet(amount.get() * -1);
        }

        @Override
        public AtomicInteger getBalance() {
            return this.balance;
        }
    }

}
